// markingPapers.js
import Toast from '@vant/weapp/toast/toast';
import {request} from '../../utils/request.js'
Page({
  onShow(){
    let vm = this
    wx.getStorage({
      key:'config.stepType',
      success(res){
        vm.setData({
          stepType: res.data || '1分',
        })
      }
    })
    wx.getStorage({
      key:'config.subType',
      success(res){
        vm.setData({
          subType: res.data || '点击提交',
        })
      }
    })
    wx.getStorage({
      key:'gradingPaper',
      success(res){
        vm.data.gradingPaper = res.data//考试信息
        wx.getStorage({
          key:'gradingPaperDetail',
          success(res){
            vm.data.gradingPaperDetail = res.data//阅卷信息
            vm.data.title = vm.data.gradingPaperDetail.reviewType==1?'阅卷':'仲裁' + ':' +vm.data.gradingPaper.examName
            vm.setData({
              title:vm.data.title
            })
            let numL = res.data.topicNumbers.split(',')
            vm.getReviewTaskByExamId(numL[0])
          }
        })
      }
    })
  },
  data: {
    scoreheight:'',
    title:'',
    gradingPaper:{},//考试信息
    gradingPaperDetail:{},//阅卷信息
    array:[],//题块列表
    scoreResVoList:[],//小题题目列表
    index:0,//当前选择的题块
    littleIndex:0,//当前选择的题
    choseNum:1,//当前选址试卷index+1
    choseData:{},//当前选择的试卷
    choseLittleData:{},//当前选择的小题
    reviewStatus:'',//试卷类型--1-阅卷中 2-已阅卷 3-待仲裁
    stepType:'1分',//步长
    imgInfo:[],//试卷图片
    imgInfoNext:{},//缓存下一页图片
    imageSrc:'/static/demo/1229A.jpg',
    limitScore:[],
    nowScore: '-',
    scale:1,
    width: '100%',
    distance: 0,
    overflow:'auto',
    subType:'点击提交',
    svgScore:'',//均分
    lastUpdate:0,
    noteList:[],//批注列表
    leftList:[//批注工具
      { active: false, noteType: 1, content: '√' },
    { active: false, noteType: 2, content: '×' },
    { active: false, noteType: 3, content: '⍻' },
    // { active: false, noteType: 4, content: '文字' },
    { active: false, noteType: 5, content: '优秀' },
    { active: false, noteType: 6, content: '反面' }],
    rightList:[],//批注工具
    resultScore:0,//得分
    piShow:false,//批注工具显示隐藏
    choseTex:null,//当前要画的文本
    lastObj:{},//当前要画的对象
  },
  piShowAction(){//标注显示隐藏
    this.data.choseTex = null
    this.data.leftList.forEach((item) => {
      item.active = false
    })
    this.data.rightList.forEach((item) => {
      item.active = false
    })
    this.setData({
      leftList:this.data.leftList,
      rightList:this.data.rightList
    })
    this.setData({
      leftList:this.data.leftList,
      rightList:this.data.rightList,
      piShow:!this.data.piShow
    })
  },
  choseTool(e){//选择标注
    let data = e.target.dataset.data
    let act = data.active
    this.data.choseTex =act?null: data
    this.data.leftList.forEach((item) => {
      if(item.content == data.content){
        item.active = !act
      }else{
        item.active = false
      }
    })
    this.data.rightList.forEach((item) => {
      if(item.content == data.content){
        item.active = !act
      }else{
        item.active = false
      }
    })
    this.data.noteList.forEach(val => {
      val.active = false
    })
    this.setData({
      leftList:this.data.leftList,
      rightList:this.data.rightList,
      noteList:this.data.noteList
    })
  },
  socreInit(){//步骤分
    this.data.rightList = []
    let max = this.data.choseLittleData.limitScore
    if(max > 10){
        max = 10
    }
    for (let i = 0; i < max; i++){
        this.data.rightList.push({ active: false, noteType: 7, content: i + 0.5,type:'+' })
        this.data.rightList.push({ active: false, noteType: 7, content: i + 1,type:'+' })
    }
    this.data.rightList.push({ active: false, content: '得分：0' })
    this.setData({
      rightList:this.data.rightList
    })
    if(this.data.noteList.length){
        setTimeout(() => {
            this.textListInt()
        }, 100)
    }
  },
  //点击cancas
  canvasClick(e){
    let item = e.target.dataset.data
    let index = e.target.dataset.index
    let x = (e.detail.x-40) * this.data.imgInfo[index].wScale
    let y = (e.detail.y- e.target.offsetTop - 60) * this.data.imgInfo[index].hScale
    if(this.data.choseTex){//添加文本
      this.data.lastObj = {
          topicNumber: this.data.choseLittleData.topicNumber,
          cropNo: index,
          id: new Date().getTime(),
          fileId: item.id,
          noteType: this.data.choseTex.noteType,
          content: this.data.choseTex.content,
          x,
          y,
          position: JSON.stringify({ x: x + Number(item.x), y: y + Number(item.y) })
      }
      this.data.noteList.push(this.data.lastObj)
      this.canvasTextInit()
    }else if(this.data.piShow){//如果点击到了批注，就可以选中并删除
      this.data.noteList.forEach(val => {
        val.active = false
      })
      let num = 99999
      let choseIndex = null
      this.data.noteList.forEach((val,i) => {
        if(Math.abs(x-val.x)<30*this.data.imgInfo[index].wScale && Math.abs(y-val.y)<30*this.data.imgInfo[index].hScale){
          let tot = Math.abs(x-val.x) + Math.abs(y-val.y)
          if(num>tot){
            num = tot
            choseIndex = i
          }
        }
      })
      if(choseIndex!==null){
        this.data.noteList[choseIndex].active = true
        this.canvasTextInit()
      }
    }

  },
  //得分重置
  textListInt(){
    let num = 0
    this.data.noteList.forEach((item) => {
        if(item.noteType == 7 && item.topicNumber == this.data.choseLittleData.topicNumber){
            num += Number(item.content)
        }
    })
    this.data.resultScore = num
    this.data.rightList[this.data.rightList.length - 1].content = '得分：' + num
    this.setData({
      rightList:this.data.rightList
    })
  },
  //平均分
  selectTopicAvgScore(){
    let vm = this
    request({
      url:'/review-paper/exam/selectTopicAvgScore',
      data:{
        subjectExamId: vm.data.array[vm.data.index].subjectExamId,
        mainNumber: vm.data.array[vm.data.index].mainNumber
      },
      success (res) {
        if(res.data.status == 1){
          res.data.data.forEach(val => {
            if(val.topicNumber== vm.data.choseLittleData.topicNumber){
              vm.setData({
                svgScore:val.svgScore
              })
            }
          })
        }else{
          Toast.fail(res.data.msg);
        }
      }
    })
  },
  //下一份未阅试卷
  nextNoYue(){
    let vm = this
    if(vm.data.array[vm.data.index].completeNum == vm.data.array[vm.data.index].totalNum){
      Toast('该题块已全部阅完')
      vm.setData({
        choseNum:vm.data.array[vm.data.index].completeNum
      })
    }else{
      vm.setData({
        choseNum:vm.data.array[vm.data.index].completeNum+1
      })
    }
    vm.getDetailReviewTask()
    vm.getDetailReviewTaskNext(vm.data.choseNum+1)//获取试卷列表

  },
  //分值列表
  scoreInit(){
    this.data.limitScore = []
    if(this.data.stepType == '1分'){
      let n = 1
      for(let i = 0; i <= this.data.choseLittleData.limitScore;i++){
          this.data.limitScore.push(n * i)
      }
    }else{
        let n = 0.5
        for(let i = 0; i <= this.data.choseLittleData.limitScore / 0.5;i++){
          this.data.limitScore.push(n * i)
        }
    }
    this.setData({
      limitScore: this.data.limitScore
    })
  },
  //获取题目信息
  getReviewTaskByExamId(topicNumber,fn){
    let vm = this
    request({
      loading:false,
      url:'/review-paper/exam/getReviewTaskByExamId',
      data:{
        examId: this.data.gradingPaper.examId,
        reviewType: this.data.gradingPaperDetail.reviewType//1阅卷 2仲裁
      },
      success (res) {
        if(res.data.status == 1){
          res.data.data.forEach(val => {
            val.reviewTaskNameC = val.reviewTaskName + '（' +val.completeNum +'/'+val.totalNum+ '）'
          })
          if(topicNumber){//默认选中哪个题
            res.data.data.forEach((val,i) => {
              if(val.mainNumber == topicNumber && val.subjectExamId == vm.data.gradingPaperDetail.subjectExamId){
                vm.data.index = i
                vm.setData({
                  index:vm.data.index
                })
              }
            })
          }
          let num = res.data.data[vm.data.index].completeNum+1
          if(num > res.data.data[vm.data.index].totalNum){
            num = res.data.data[vm.data.index].totalNum
          }
          vm.setData({
            array:res.data.data,
            // choseNum:res.data.data[vm.data.index].completeNum+1
          })
          if(!fn){
            vm.getDetailReviewTask()
            vm.getDetailReviewTaskNext(vm.data.choseNum+1)//获取试卷列表
          }
          fn && fn()
        }else{
          Toast.fail(res.data.msg);
        }
      }
    })
  },
  //获取试卷新列表
  getDetailReviewTask(){
    let vm = this
    request({
      url:'/review-paper/exam/getDetailReviewTask',
      data:{
        subjectExamId: vm.data.array[vm.data.index].subjectExamId,
        mainNumber: vm.data.array[vm.data.index].mainNumber,
        reviewType: vm.data.gradingPaperDetail.reviewType,//1阅卷 2仲裁
        reviewStatus: vm.data.reviewStatus,
        page: vm.data.choseNum
      },
      success (res) {
        if(res.data.status == 1){
          vm.getDetailReviewTaskFn(res.data.data)
        }else{
          Toast.fail(res.data.msg);
        }
      }
    })
  },
  //获取试卷新列表
  getDetailReviewTaskNext(page){
    let vm = this
    if(page > this.data.array[this.data.index].totalNum){
      vm.setData({
        imgInfoNext:{}
      })
      return
    }
    request({
      url:'/review-paper/exam/getDetailReviewTask',
      data:{
        subjectExamId: vm.data.array[vm.data.index].subjectExamId,
        mainNumber: vm.data.array[vm.data.index].mainNumber,
        reviewType: vm.data.gradingPaperDetail.reviewType,//1阅卷 2仲裁
        reviewStatus: vm.data.reviewStatus,
        page: page
      },
      success (res) {
        if(res.data.status == 1){
          vm.setData({
            imgInfoNext:res.data.data||{}
          })
        }
      }
    })
  },
  getDetailReviewTaskFn(data){
    let vm = this
    let chose = data
    vm.setData({
      choseData: chose,
      scoreResVoList:chose.scoreResVoList,
      scoreheight:chose.scoreResVoList.length * 20 + 30+'px',
      choseLittleData:chose.scoreResVoList[0],
      nowScore:chose.reviewScore === null?'-':chose.reviewScore
    })
    //图片
    vm.data.imgInfo = chose.imgList
    vm.setData({
      imgInfo:vm.data.imgInfo
    })
    vm.scoreInit()//分值重置
    vm.selectTopicAvgScore()//均分
    
    vm.socreInit()//步骤分重置
    // let num=100
    // setInterval(() => {
    //   num++
    //   vm.setData({
    //     width: num + '%'
    //   })
    // }, 100);
    //查询批注
    vm.data.imgInfo.forEach((val, i) => {
      wx.getImageInfo({
        src: val.filePath,
        success(res) {
          val.width = res.width;  // 图片原始宽度
          val.height = res.height; // 图片原始高度
          const query = wx.createSelectorQuery();
          vm.findReviewNote()
          // 在页面中选择你想要查询的节点
          setTimeout(() => {
            query.select('.resizable-image'+i) // 替换为你的元素的选择器
            .boundingClientRect(function(rect) {  
              val.w = rect.width
              val.wScale = val.width/ val.w
              val.h = rect.height
              val.hScale = val.height/val.h
            })
            .exec(); // 执行查询
          }, 1000);
        }
      });
    })
  },
  onTouchEnd(){
    this.setData({
      overflow:'auto'
    })
  },
  onTouchMove: function (e) {
      if (e.touches.length === 2) {  
        this.setData({
          overflow:'hidden'
        })
        let Xm = e.touches[1].clientX - e.touches[0].clientX
        let Ym = e.touches[1].clientY - e.touches[0].clientY
        let newDistance = Math.sqrt(Xm * Xm + Ym * Ym)
        if(Math.abs(newDistance - this.data.distance)<5){
          return
        }
        if(newDistance > this.data.distance){
          if(this.data.scale<=3){
            this.data.scale = this.data.scale+0.05
          }
        }else{
          if(this.data.scale>=0.2){
            this.data.scale = this.data.scale-0.05
          }
        }
        this.data.distance = newDistance

        this.data.width = parseInt(this.data.scale*100 + '%')
        const now = Date.now()
        if (now - this.data.lastUpdate < 32) return // 限制 30fps
        this.data.lastUpdate = now
        this.setData({
          scale: this.data.scale,
          width: parseInt(this.data.scale*100) + '%'
        })
      }  
  },
    //选择小题
    littleBindTap:function(e) {
      var index = e.currentTarget.dataset.index;  
      this.setData({
        littleIndex: index,
        choseLittleData:this.data.scoreResVoList[index]
      })
      this.scoreInit()
      this.selectTopicAvgScore()//均分
      this.socreInit()//步骤分重置
    },
  //选择分数
  bindTap:function(e) {
    var index = e.currentTarget.dataset.index; // 获取按钮的数据索引 
    this.data.choseLittleData.reviewScore = this.data.scoreResVoList[this.data.littleIndex].reviewScore = this.data.limitScore[index]
    this.setData({
      choseLittleData:this.data.choseLittleData,
      scoreResVoList: this.data.scoreResVoList
    })
    if(this.data.scoreResVoList[this.data.littleIndex+1]){//如果有下一个小题，直接选中下个小题
      this.data.choseLittleData = this.data.scoreResVoList[this.data.littleIndex+1]
      this.data.littleIndex = this.data.littleIndex+1
      this.setData({
        choseLittleData:this.data.choseLittleData,
        littleIndex: this.data.littleIndex
      })
      this.scoreInit()
      this.selectTopicAvgScore()//均分
    }else{//没有下一小题，直接保存打分
      if(this.data.subType == '自动提交' && this.data.scoreResVoList.every(val=>val.reviewScore>0||val.reviewScore===0)){
        this.data.littleIndex
        this.saveReviewScore()
      }
    }
    
  },
  //步长
  bindPickerChange: function(e) {
    this.setData({
      stepType: e.detail.value
    })
    this.scoreInit()
  },
  //选择任务
  bindRadioChange: function(e) {
    let vm = this
    let num = vm.data.array[e.detail.value].completeNum+1
    if(num > vm.data.array[e.detail.value].totalNum){
      num = vm.data.array[e.detail.value].totalNum
    }
    this.setData({
      index: e.detail.value,
      choseData:{},
      choseNum:num
    })
    this.getDetailReviewTask()//获取试卷列表
   
    this.getDetailReviewTaskNext(this.data.choseNum+1)
  },
  //上一份
  prePaper(){
    if(this.data.choseNum == 1){
      Toast('已经是第一份了')
      return
    }
    this.setData({
      choseNum: this.data.choseNum-1,
      littleIndex: 0
    })
    this.setData({
      imgInfoNext:this.data.choseData
    })
    this.getDetailReviewTask()

  },
  //下一份
  nextPaper(){
    if(this.data.choseNum == this.data.array[this.data.index].totalNum){
      if(this.data.array[this.data.index+1]){
        let num = this.data.array[this.data.index+1].completeNum+1
        if(num > this.data.array[this.data.index+1].totalNum){
          num = this.data.array[this.data.index+1].totalNum
        }
        this.setData({
          index: this.data.index+1,
          littleIndex: 0,
          choseNum:num
        })
        this.getDetailReviewTask()
        this.getDetailReviewTaskNext(this.data.choseNum+1)//获取试卷列表
      }else{
        Toast('已经是最后一份了')
      }
      return
    }
    this.data.littleIndex = 0
    this.setData({
      choseNum: this.data.choseNum+1,
      littleIndex: 0
    })
    if(this.data.imgInfoNext.imgList){
      this.getDetailReviewTaskFn(this.data.imgInfoNext)
      this.getDetailReviewTaskNext(this.data.choseNum+1)//获取试卷列表
    }
  },
  //提交打分
  saveReviewScore(){
    if(this.data.scoreResVoList.length == 0){
      Toast('没有题目')
      return
    }
    let arr = []
    this.data.scoreResVoList.forEach((val) => {
        if(!val.reviewScore && val.reviewScore != 0){
            arr.push(val.topicNumber)
        }
    })
    if(arr.length > 0){
      Toast('第' + arr.join('、') + '题未打分')
      return
    }
    let topicList = this.data.scoreResVoList.map((val) => {
      return {
          topicNumber: val.topicNumber,
          topicScore: val.reviewScore
      }
  })
    let vm = this
    wx.getStorage({key:'token',
    success(res){
      request({
        url:'/review-paper/exam/saveReviewScore',
        header:{
          'content-type': 'application/json',
          accessToken: res.data
        },
        data:{
          subjectExamId: vm.data.array[vm.data.index].subjectExamId,
          studentId: vm.data.choseData.studentId,
          reviewType: vm.data.gradingPaperDetail.reviewType,//1阅卷 2仲裁
          mainNumber: vm.data.array[vm.data.index].mainNumber,
          topicList
        },
        success (res) {
          if(res.data.status == 1){
            Toast.success({
              message:res.data.msg,
              duration: 500
            })
            vm.saveNote()//保存批注
          }else{
            Toast.fail(res.data.msg);
          }
        }
      })
    }
  })
  },
  //跳转视频号
  navigateToChannel: function() {
    wx.openChannelsUserProfile({
      finderUserName:getApp().globalData.sphId,
      complete(e){
        console.log(e)
      }
    })
  },
  
  //查询批注
  findReviewNote(){
    let vm = this
    request({
      loading:false,
      url:'/review-paper/exam/findReviewNote',
      data:{
        subjectExamId: vm.data.array[vm.data.index].subjectExamId,
        mainNumber: vm.data.array[vm.data.index].mainNumber,
        studentId: vm.data.choseData.studentId
      },
      success (res) {
        if(res.data.status == 1){
          res.data.data.forEach((val, i) =>{
              let positon = JSON.parse(val.position)
              let x = positon.x - vm.data.imgInfo[val.cropNo].x
              let y = positon.y - vm.data.imgInfo[val.cropNo].y
              // val.id = createHash()
              val.x = x
              val.y = y
          })
          vm.data.noteList = res.data.data
          vm.canvasTextInit()
        }else{
          Toast.fail(res.data.msg);
        }
      }
    })
  },
  //绘制批注
  canvasTextInit(){
      let canvasArray = []
      this.data.imgInfo.forEach((item, i) => {
        const query = wx.createSelectorQuery()
        query.select('#canvas'+i)
        .fields({ node: true, size: true })
        .exec((res) => {
          const myCanvasText = res[0].node
          const ctx = myCanvasText.getContext('2d')
          myCanvasText.width = item.width
          myCanvasText.height = item.height 
          ctx.clearRect(0, 0, myCanvasText.width, myCanvasText.height)
          canvasArray.push(ctx)
          if(this.data.noteList.length && canvasArray.length == this.data.imgInfo.length){
            this.data.noteList.forEach((item) => {
                  canvasArray[item.cropNo].font = '40px Arial'
                  canvasArray[item.cropNo].fillStyle = item.active?'blue': 'red'
                  canvasArray[item.cropNo].fillText(item.content, item.x, item.y)
              })
          }
        })
      })
      //计算得分
      this.textListInt()
  },
  //清除标记
  clearTool() {
    this.data.noteList = []
    this.canvasTextInit()
  },
  //删除标记
  deletePi(){
    this.data.noteList = this.data.noteList.filter(val =>!val.active)
    this.canvasTextInit()
  },
  //提交批注
  saveNote(){
    let vm = this
    debugger
    request({
      loading:false,
      url:'/review-paper/exam/saveNote',
      data:{
        subjectExamId: vm.data.array[vm.data.index].subjectExamId,
        mainNumber: vm.data.array[vm.data.index].mainNumber,
        studentId: vm.data.choseData.studentId,
        noteList: JSON.stringify(vm.data.noteList)
      },
      success (res) {
        if(res.data.status == 1){
          vm.getReviewTaskByExamId(null,()=>{
            vm.nextPaper()
          })
        }
      }
    })
}
})


